import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Material Design 3风格的天气趋势图组件
 * 绘制14天气温变化趋势图，支持现代化设计和交互显示
 */
public class WeatherTrendChart extends JPanel {
    private WeatherData[] forecastData;
    private int chartWidth;
    private int chartHeight;
    private int padding = 50;
    
    // Material Design 3 色彩系统
    private Color surfaceColor = new Color(248, 250, 252); // Surface container
    private Color primaryColor = new Color(103, 80, 164); // Primary
    private Color primaryContainerColor = new Color(234, 221, 255); // Primary container
    private Color onSurfaceColor = new Color(28, 27, 31); // On surface
    private Color onSurfaceVariantColor = new Color(73, 69, 79); // On surface variant
    private Color outlineColor = new Color(121, 116, 126); // Outline
    private Color tertiaryColor = new Color(125, 82, 96); // Tertiary
    private Color errorColor = new Color(186, 26, 26); // Error
    
    // 渐变色彩
    private Color gradientStart = new Color(103, 80, 164, 60); // 半透明primary
    private Color gradientEnd = new Color(103, 80, 164, 10); // 更透明的primary
    
    public WeatherTrendChart() {
        setBackground(surfaceColor);
        setPreferredSize(new Dimension(800, 640)); // 增加高度以提供更好的视觉效果
        setBorder(createModernBorder());
        setOpaque(true);
    }
    
    /**
     * 创建Material Design 3风格的边框
     */
    private javax.swing.border.Border createModernBorder() {
        return BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(outlineColor, 1),
            BorderFactory.createEmptyBorder(16, 16, 16, 16)
        );
    }
    
    /**
     * 更新趋势图数据
     * @param data 14天预报数据数组
     */
    public void updateData(WeatherData[] data) {
        this.forecastData = data;
        repaint();
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        Graphics2D g2d = (Graphics2D) g.create();
        // 启用高质量渲染
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        
        // 绘制圆角背景卡片
        drawModernBackground(g2d);
        
        if (forecastData == null || forecastData.length == 0) {
            drawNoDataMessage(g2d);
            g2d.dispose();
            return;
        }
        
        chartWidth = getWidth() - 2 * padding;
        chartHeight = getHeight() - 2 * padding - 40; // 为标题留出空间
        
        // 绘制标题
        drawModernTitle(g2d);
        
        // 绘制现代化网格
        drawModernGrid(g2d);
        
        // 绘制温度趋势区域填充
        drawTemperatureArea(g2d);
        
        // 绘制温度趋势线
        drawModernTemperatureTrend(g2d);
        
        // 绘制现代化数据点
        drawModernDataPoints(g2d);
        
        // 绘制坐标轴标签
        drawModernAxisLabels(g2d);
        
        g2d.dispose();
    }
    
    /**
     * 绘制现代化背景
     */
    private void drawModernBackground(Graphics2D g2d) {
        // 绘制圆角矩形背景
        RoundRectangle2D background = new RoundRectangle2D.Float(
            0, 0, getWidth(), getHeight(), 24, 24);
        g2d.setColor(surfaceColor);
        g2d.fill(background);
        
        // 添加微妙的阴影效果
        g2d.setColor(new Color(0, 0, 0, 8));
        g2d.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 24, 24);
    }
    
    /**
     * 绘制现代化标题
     */
    private void drawModernTitle(Graphics2D g2d) {
        g2d.setColor(onSurfaceColor);
        g2d.setFont(new Font("Segoe UI", Font.BOLD, 18));
        String title = "14-Day Temperature Trend";
        FontMetrics fm = g2d.getFontMetrics();
        int titleX = padding;
        int titleY = 25;
        g2d.drawString(title, titleX, titleY);
        
        // 绘制副标题
        g2d.setColor(onSurfaceVariantColor);
        g2d.setFont(new Font("Segoe UI", Font.PLAIN, 12));
        String subtitle = "Daily temperature forecast with trend analysis";
        g2d.drawString(subtitle, titleX, titleY + 16);
    }
    
    /**
     * 绘制无数据提示（现代化风格）
     */
    private void drawNoDataMessage(Graphics2D g2d) {
        g2d.setColor(onSurfaceVariantColor);
        g2d.setFont(new Font("Segoe UI", Font.PLAIN, 16));
        String message = "No forecast data available";
        FontMetrics fm = g2d.getFontMetrics();
        int x = (getWidth() - fm.stringWidth(message)) / 2;
        int y = getHeight() / 2;
        g2d.drawString(message, x, y);
        
        // 绘制图标占位符
        g2d.setColor(outlineColor);
        int iconSize = 24;
        int iconX = x - iconSize - 8;
        int iconY = y - iconSize/2;
        g2d.drawOval(iconX, iconY, iconSize, iconSize);
        g2d.drawLine(iconX + 6, iconY + 12, iconX + 18, iconY + 12);
    }
    
    /**
     * 绘制现代化网格
     */
    private void drawModernGrid(Graphics2D g2d) {
        g2d.setColor(new Color(outlineColor.getRed(), outlineColor.getGreen(), outlineColor.getBlue(), 30));
        g2d.setStroke(new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{2, 4}, 0));
        
        int chartTop = padding + 40;
        
        // 垂直网格线（天数）
        int days = Math.min(forecastData.length, 14);
        for (int i = 0; i <= days; i++) {
            int x = padding + (chartWidth * i) / days;
            g2d.drawLine(x, chartTop, x, chartTop + chartHeight);
        }
        
        // 水平网格线（温度）
        int gridLines = 5;
        for (int i = 0; i <= gridLines; i++) {
            int y = chartTop + (chartHeight * i) / gridLines;
            g2d.drawLine(padding, y, padding + chartWidth, y);
        }
    }
    
    /**
     * 绘制温度区域填充
     */
    private void drawTemperatureArea(Graphics2D g2d) {
        if (forecastData.length < 2) return;
        
        double[] tempRange = getTemperatureRange();
        double minTemp = tempRange[0];
        double maxTemp = tempRange[1];
        double tempSpan = maxTemp - minTemp;
        
        if (tempSpan < 0.1) {
            tempSpan = 10;
            minTemp -= 5;
            maxTemp += 5;
        }
        
        int chartTop = padding + 40;
        int days = Math.min(forecastData.length, 14);
        
        // 创建温度区域路径
        Path2D.Double areaPath = new Path2D.Double();
        
        for (int i = 0; i < days; i++) {
            double temp = forecastData[i].getTemperatureCelsius();
            int x = padding + (chartWidth * i) / (days - 1);
            int y = chartTop + (int) ((maxTemp - temp) * chartHeight / tempSpan);
            
            if (i == 0) {
                areaPath.moveTo(x, y);
            } else {
                areaPath.lineTo(x, y);
            }
        }
        
        // 连接到底部形成封闭区域
        areaPath.lineTo(padding + chartWidth, chartTop + chartHeight);
        areaPath.lineTo(padding, chartTop + chartHeight);
        areaPath.closePath();
        
        // 创建渐变填充
        GradientPaint gradient = new GradientPaint(
            0, chartTop, gradientStart,
            0, chartTop + chartHeight, gradientEnd
        );
        g2d.setPaint(gradient);
        g2d.fill(areaPath);
    }
    
    /**
     * 绘制现代化温度趋势线
     */
    private void drawModernTemperatureTrend(Graphics2D g2d) {
        if (forecastData.length < 2) return;
        
        double[] tempRange = getTemperatureRange();
        double minTemp = tempRange[0];
        double maxTemp = tempRange[1];
        double tempSpan = maxTemp - minTemp;
        
        if (tempSpan < 0.1) {
            tempSpan = 10;
            minTemp -= 5;
            maxTemp += 5;
        }
        
        int chartTop = padding + 40;
        int days = Math.min(forecastData.length, 14);
        
        // 创建温度曲线路径
        Path2D.Double path = new Path2D.Double();
        
        for (int i = 0; i < days; i++) {
            double temp = forecastData[i].getTemperatureCelsius();
            int x = padding + (chartWidth * i) / (days - 1);
            int y = chartTop + (int) ((maxTemp - temp) * chartHeight / tempSpan);
            
            if (i == 0) {
                path.moveTo(x, y);
            } else {
                path.lineTo(x, y);
            }
        }
        
        // 绘制趋势线（更粗，使用primary色）
        g2d.setColor(primaryColor);
        g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g2d.draw(path);
    }
    
    /**
     * 绘制现代化数据点
     */
    private void drawModernDataPoints(Graphics2D g2d) {
        double[] tempRange = getTemperatureRange();
        double minTemp = tempRange[0];
        double maxTemp = tempRange[1];
        double tempSpan = maxTemp - minTemp;
        
        if (tempSpan < 0.1) {
            tempSpan = 10;
            minTemp -= 5;
            maxTemp += 5;
        }
        
        int chartTop = padding + 40;
        int days = Math.min(forecastData.length, 14);
        
        for (int i = 0; i < days; i++) {
            double temp = forecastData[i].getTemperatureCelsius();
            int x = padding + (chartWidth * i) / (days - 1);
            int y = chartTop + (int) ((maxTemp - temp) * chartHeight / tempSpan);
            
            // 绘制外圈（白色背景）
            g2d.setColor(surfaceColor);
            g2d.fillOval(x - 6, y - 6, 12, 12);
            
            // 绘制内圈（primary色）
            g2d.setColor(primaryColor);
            g2d.fillOval(x - 4, y - 4, 8, 8);
            
            // 绘制温度标签（现代化字体）
            g2d.setColor(onSurfaceColor);
            g2d.setFont(new Font("Segoe UI", Font.BOLD, 11));
            String tempLabel = String.format("%.0f°", temp);
            FontMetrics fm = g2d.getFontMetrics();
            int labelX = x - fm.stringWidth(tempLabel) / 2;
            int labelY = y - 12;
            
            // 确保标签不超出边界
            if (labelY < chartTop) labelY = y + 24;
            
            // 绘制标签背景
            int bgPadding = 3;
            g2d.setColor(new Color(255, 255, 255, 200));
            g2d.fillRoundRect(labelX - bgPadding, labelY - fm.getAscent() - bgPadding, 
                fm.stringWidth(tempLabel) + 2 * bgPadding, fm.getHeight() + 2 * bgPadding, 4, 4);
            
            g2d.setColor(onSurfaceColor);
            g2d.drawString(tempLabel, labelX, labelY);
        }
    }
    
    /**
     * 绘制现代化坐标轴标签
     */
    private void drawModernAxisLabels(Graphics2D g2d) {
        g2d.setColor(onSurfaceVariantColor);
        g2d.setFont(new Font("Segoe UI", Font.PLAIN, 10));
        
        int chartTop = padding + 40;
        int days = Math.min(forecastData.length, 14);
        
        // 绘制日期标签（每隔一天显示）
        for (int i = 0; i < days; i += 2) {
            int x = padding + (chartWidth * i) / (days - 1);
            int y = getHeight() - 15;
            
            String dayLabel = String.format("Day %d", i + 1);
            FontMetrics fm = g2d.getFontMetrics();
            int labelX = x - fm.stringWidth(dayLabel) / 2;
            
            g2d.drawString(dayLabel, labelX, y);
        }
        
        // 绘制温度刻度标签
        double[] tempRange = getTemperatureRange();
        double minTemp = tempRange[0];
        double maxTemp = tempRange[1];
        double tempSpan = maxTemp - minTemp;
        
        if (tempSpan < 0.1) {
            tempSpan = 10;
            minTemp -= 5;
            maxTemp += 5;
        }
        
        int gridLines = 5;
        for (int i = 0; i <= gridLines; i++) {
            int y = chartTop + (chartHeight * i) / gridLines;
            double temp = maxTemp - (tempSpan * i) / gridLines;
            
            String tempLabel = String.format("%.0f°C", temp);
            FontMetrics fm = g2d.getFontMetrics();
            g2d.drawString(tempLabel, padding - fm.stringWidth(tempLabel) - 8, y + fm.getAscent()/2);
        }
    }
    
    /**
     * 计算温度范围
     */
    private double[] getTemperatureRange() {
        if (forecastData == null || forecastData.length == 0) {
            return new double[]{0, 30};
        }
        
        double minTemp = Double.MAX_VALUE;
        double maxTemp = Double.MIN_VALUE;
        
        int days = Math.min(forecastData.length, 14);
        for (int i = 0; i < days; i++) {
            double temp = forecastData[i].getTemperatureCelsius();
            minTemp = Math.min(minTemp, temp);
            maxTemp = Math.max(maxTemp, temp);
        }
        
        // 添加一些边距以获得更好的视觉效果
        double margin = (maxTemp - minTemp) * 0.1;
        minTemp -= margin;
        maxTemp += margin;
        
        return new double[]{minTemp, maxTemp};
    }
} 